#include "stdafx.h"
#include <string.h>

#include "IniReader.h"

#ifdef _DEBUG
#include "crtdbg.h"
#endif

CSimpleIniW IniReader::ini(true, false, false);

const TCHAR IniReader::sectionMain[] = TEXT("main");
const TCHAR IniReader::sectionLang[] = TEXT("language");
const TCHAR IniReader::sectionSkin[] = TEXT("theme");

const TCHAR IniReader::settings[] = TEXT("settings.ini");

bool IniReader::Create()
{
    TCHAR szIniPath[MAX_PATH];
    TCHAR szLanguagePath[MAX_PATH];
    TCHAR szThemePath[MAX_PATH];

    // Get program file path
    GetModuleFileName(NULL, szIniPath, MAX_PATH);

    TCHAR * pstr = _tcsrchr(szIniPath, TEXT('\\'));
    if (pstr) *(++pstr) = 0;

    StringCchCopy(szLanguagePath, MAX_PATH, szIniPath);
    StringCchCat(szLanguagePath, MAX_PATH, INI_LANGUAGE_PATH);

    StringCchCopy(szThemePath, MAX_PATH, szIniPath);
    StringCchCat(szThemePath, MAX_PATH, INI_THEME_PATH);

    StringCchCat(szIniPath, MAX_PATH, IniReader::settings);

    SI_Error res;

    res = IniReader::ini.LoadFile(szIniPath);
    if (res < 0)
      return false;

    StringCchCat(szLanguagePath, MAX_PATH, ini.GetValue(
      IniReader::sectionMain, TEXT("Language"), TEXT("english")));
    StringCchCat(szLanguagePath, MAX_PATH, TEXT(".lng"));
    res = IniReader::ini.LoadFile(szLanguagePath);

    StringCchCat(szThemePath, MAX_PATH, ini.GetValue(
      IniReader::sectionMain, TEXT("Skin"), TEXT("default")));
    StringCchCat(szThemePath, MAX_PATH, TEXT(".skn"));
    res = IniReader::ini.LoadFile(szThemePath);

    return true;
}

void IniReader::Destroy()
{
  IniReader::ini.Reset();
}

int IniReader::getColor(const TCHAR* section, const TCHAR* key, const TCHAR* defVal)
{
  const TCHAR* scolor = IniReader::ini.GetValue(section, key, defVal);
  if (_tcslen(scolor) != 6)
    scolor = defVal;

  TCHAR red[3];
  TCHAR green[3];
  TCHAR blue[3];
  StringCchCopy(red, 3, scolor);
  StringCchCopy(green, 3, scolor + 2);
  StringCchCopy(blue, 3, scolor + 4);
  int r = _tcstol(red, NULL, 16);
  int g = _tcstol(green, NULL, 16);
  int b = _tcstol(blue, NULL, 16);

  return RGB(r, g, b);  
}
